<template>
  <a-form
    class="form"
    :label-col="{ span: 6 }"
    :wrapper-col="{ span: 18 }"
    :model="formData"
    :rules="rules"
    @finish="onFinish"
  >
      <a-form-item name="mavenHome" label="Maven目录">
        <path-input v-model:value="formData.mavenHome" />
      </a-form-item>
      <a-form-item name="localRepository" label="仓库路径">
        <path-input v-model:value="formData.localRepository" />
      </a-form-item>
      <a-form-item name="pomPath" label="pom文件">
        <path-input v-model:value="formData.pomPath" type="file" :extensions="['xml']" />
      </a-form-item>
      <a-form-item name="mirror" label="镜像源">
        <mirror-inpupt :mirrors="mavenMirrors" v-model:mirror="formData.mirror" />
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 8, offset: 8 }">
        <a-button type="primary" style="width: 100%" html-type="submit">下载</a-button>
      </a-form-item>
  </a-form>
</template>

<script setup>
import { reactive, onMounted } from 'vue'
import {mavenMirrors} from '@/common/default'

const emit = defineEmits(['finish'])

const rules = {
  mavenHome: [
    {
      required: true,
      message: '无效的路径',
      trigger: 'blur',
      validator: async (rule, val) => {
        const result = await window.electronAPI.isValidPath(`${val}/bin/mvn`)
        return result ? Promise.resolve() : Promise.reject()
      }
    }
  ],
  mirror: [
    {
      required: true,
      message: '请填写镜像源',
      trigger: 'blur',
      validator: (rule, mirror) => {
        return mirror.url ? Promise.resolve() : Promise.reject()
      }
    }
  ],
  localRepository: [
    {
      required: true,
      message: '无效的路径',
      trigger: 'blur',
      validator: async (rule, val) => {
        const result = await window.electronAPI.isValidPath(val)
        return result ? Promise.resolve() : Promise.reject()
      }
    }
  ],
  pomPath: [
    {
      required: true,
      message: '无效的路径',
      trigger: 'blur',
      validator: async (rule, val) => {
        const result = await window.electronAPI.isValidPath(val)
        return result ? Promise.resolve() : Promise.reject()
      }
    }
  ]
}

const formData = reactive({
  mavenHome: '',
  localRepository: '',
  pomPath: '',
  mirror: mavenMirrors[0]
})

onMounted(async () => {
  const mavenHome = await window.electronAPI.getMavenHome()
  formData.mavenHome = mavenHome
})

const onFinish = (values) => {
    emit('finish', values)
}
</script>

<style scoped>
.form {
    width: 100%;
}
</style>